package stu.xjtu.physical.interceptor;



import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import stu.xjtu.physical.common.constant.JwtClaimsConstant;
import stu.xjtu.physical.common.properties.JwtProperties;
import stu.xjtu.physical.common.utls.BaseContext;
import stu.xjtu.physical.common.utls.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle开始进行JWT校验");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            log.info("不是controller的方法，我放行了");
            //当前拦截到的不是动态方法，直接放行
            return true;
        }




        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());



        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户的id:{}", empId);
            // 把当前用户的id存入线程中去
            BaseContext.setCurrentId(empId);


            //其实可以加个if判断token超过多少分钟才续签
            String tokenNew = addNewToken(BaseContext.getCurrentId());
            log.info("续签上token，新的token为{}", tokenNew);
            response.addHeader("Authorization" ,"Bearer "+tokenNew);
            log.info(response.getHeader("Authorization"));
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

    private String addNewToken(Long userId){
        Map<String, Object> claimsNew = new HashMap<>();
        claimsNew.put(JwtClaimsConstant.USER_ID,userId);
        log.info("新payload的User——id是{}",claimsNew.get(JwtClaimsConstant.USER_ID).toString());
        return JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(),claimsNew);
    }
}
